package com.zywl.utils.utils;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


/**
 * @Classname SSLClient
 * @Description TODO
 * @Date 2020/5/21 15:54
 * @Created by 小徐
 */
public class SSLClient {
   public static CloseableHttpClient createSSLClient(){
      SSLContext sslContext = null;
      try {
          sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
             @Override
             public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                //通过所有证书
                return true;
             }
          }).build();
         SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
               //不验证hostName
               return true;
            }
         });
         //如果异常了,创建普通的client
         return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
      }catch (Exception e){
         e.printStackTrace();
      }
      return HttpClients.createDefault();
   }
}
